package com.example.healthapp.utils;

import android.content.ContentValues;
import android.content.Context;
import android.database.AbstractWindowedCursor;
import android.database.Cursor;
import android.database.CursorWindow;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;

import java.util.ArrayList;
import java.util.HashMap;

// 本地数据库操作类
public class MySQLiteUtil {

    private DBOpenHelper dbOpenHelper;
    private SQLiteDatabase sqLiteDatabase;
    private static MySQLiteUtil mySQLiteControl;

    public static MySQLiteUtil getInstance(Context context, String baseName) {
        if (mySQLiteControl == null) {
            mySQLiteControl = new MySQLiteUtil();
            mySQLiteControl.dbOpenHelper = new DBOpenHelper(context, baseName, null, 1);
            mySQLiteControl.sqLiteDatabase = mySQLiteControl.dbOpenHelper.getWritableDatabase();
        }
        return mySQLiteControl;
    }

    /**
     * 增加数据
     */
    public void addContentValue(String tableName, ContentValues data) {
        sqLiteDatabase.insert(tableName, null, data);
    }

    /**
     * 删除数据
     */
    public int delete(String tableName, String whereClause, String[] whereArgs) {
        int count = sqLiteDatabase.delete(tableName, whereClause, whereArgs);
        return count; //返回删除的行数
    }

    /**
     * 查询数据
     */
    public ArrayList<HashMap<String, String>> getData(String tableName, String[] columns, String selection, String[] selectionArgs) {
        //错误
        ArrayList<HashMap<String, String>> arrayList = new ArrayList();
        HashMap<String, String> hashMap = new HashMap<>();
        Cursor cursor = sqLiteDatabase.query(tableName, columns, selection, selectionArgs, null, null, null);
        {  //设置游标最大储存量
            CursorWindow cw = null;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                cw = new CursorWindow("test", 5000000);
            }
            AbstractWindowedCursor ac = (AbstractWindowedCursor) cursor;
            ac.setWindow(cw);
        }
        while (cursor.moveToNext()) {
            hashMap = new HashMap<>();
            for (int i = 0; i < cursor.getColumnCount(); i++) {
                hashMap.put(cursor.getColumnName(i), cursor.getString(i));
            }
            arrayList.add(hashMap);
        }
        cursor.close();
        return arrayList;
    }

    /**
     * 建表语句
     */
    public void setCreateTable(String otherGeneral) {
        //建表语句
        if (otherGeneral == null) otherGeneral = dbOpenHelper.otherGeneral;
        sqLiteDatabase.execSQL(otherGeneral);
    }

    /**
     * 开启事务
     */
    public void beginTransaction() {
        sqLiteDatabase.beginTransaction();
    }

    /**
     * 提交并结束事务
     */
    public void endTransaction() {
        sqLiteDatabase.setTransactionSuccessful(); //成功提交
        sqLiteDatabase.endTransaction();
    }

    /**
     * 关闭数据库
     */
    public void closeDB() {
        sqLiteDatabase.close();
    }
}